import {Promise} from 'es6-promise';
import {Role} from "../core/defines";
import * as utils from '../core/utils';
import {MongoColls} from '../config/mongo';
import {CursorType} from "../core/defines";
import {BaseModel} from "../core/base.model";
import {Collection, ObjectID} from "mongodb";
import {
    FindParam,
    CountParam,
    UpdateParam,
    FindOneParam,
    AggregateParam,
    FindOneUpdateParam, InsertParam,
} from "../core/params";

export enum CouponStatus {
    VALID = 0x01,   //有效
    USED = 0x02,    //已使用
    LOCK = 0x03,    //锁定
    INVALID = 0x04, //过期失效
}

export interface CouponInfo {
    _id?: ObjectID,
    user_id?: ObjectID,
    code?: string,
    name: string,
    type?: number,
    stime: Date,
    etime: Date,
    limit?: number,
    amount?: number,
    status?: CouponStatus,
    time?: Date
}

export interface CouponFilter {
    _id?: ObjectID,
    user_id?: ObjectID,
    code?: string,
    page?: number,
    limit?: number,
}

export default class CouponModel extends BaseModel {
    name() {
        return 'CouponModel';
    }

    constructor(coll: Collection) {
        super(coll);
    }

    checkExist(filter: CouponFilter): Promise<any> {
        return this.findOne(new FindOneParam(filter));
    }

    receive(coupon: CouponInfo): Promise<any> {
        coupon.time = new Date();
        coupon.status = CouponStatus.VALID;
        return this.insertOne(new InsertParam(coupon));
    };

    getCoupons(filter: CouponFilter): Promise<any> {
        let {user_id, page, limit} = filter;

        let match = {
            user_id
        };

        let count;
        return this.count(new CountParam(match)).then((totalCount) => {
            count = totalCount;
            let options = new FindParam(match, {});
            options.sort = {'time': -1};
            options.skip = page * limit;
            options.limit = limit;
            return this.find(options);
        }).then((records) => {
            return {
                limit,
                curr_page: page,
                total_count: count,
                records: records || [],
                total_page: Math.ceil(count / limit)
            };
        });
    };

}
